package cn.bon.schedule.service.impl;

import cn.bon.schedule.api.pojo.dto.AddSchedulePlanDTO;
import cn.bon.schedule.api.pojo.dto.RealTimeScheduleDTO;
import cn.bon.schedule.api.pojo.po.ScheduPlan;
import cn.bon.schedule.api.pojo.po.UniScheduPlanWorkOrder;
import cn.bon.schedule.mapper.ScheduPlanMapper;
import cn.bon.schedule.service.RealTimeScheduleService;
import cn.bon.schedule.service.ScheduPlanService;
import cn.bon.schedule.service.UniScheduPlanWorkOrderService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 排班表 服务实现类
 * </p>
 *
 * @author LuoChao
 * @since 2023-12-14
 */
@Service
public class ScheduPlanServiceImpl extends ServiceImpl<ScheduPlanMapper, ScheduPlan> implements ScheduPlanService {

    @Resource
    RealTimeScheduleService realTimeScheduleService;

    @Resource
    UniScheduPlanWorkOrderService banciService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 添加排班
     * @param schedulePlanDTO
     */
    @Override
    @Transactional
    public void add(AddSchedulePlanDTO schedulePlanDTO) {
        //1.添加排班方案
        //1.1 属性复制
        ScheduPlan scheduPlan = new ScheduPlan();
        BeanUtil.copyProperties(schedulePlanDTO, scheduPlan);
        //1.2 插入并获取排班id
        this.save(scheduPlan);
        Long scheduleId = scheduPlan.getScheduPlanId();

        //2.添加班次
        Long[] workOrderIds = schedulePlanDTO.getWorkOrderIds();
        UniScheduPlanWorkOrder scheduPlanWorkOrder = new UniScheduPlanWorkOrder()
                .setScheduPlanId(scheduleId);
        for (Long workOrderId : workOrderIds) {
            scheduPlanWorkOrder.setWorkOrderId(workOrderId);
            banciService.save(scheduPlanWorkOrder);
        }

        //3.添加实时排班
        RealTimeScheduleDTO[] realTimeScheduleDTOS = schedulePlanDTO.getRealTimeScheduleDTOS();
        realTimeScheduleService.add(realTimeScheduleDTOS, scheduleId);

        //4.消息队列，计算工时和排班冲突检测
        rabbitTemplate.convertAndSend("bon.detect",null, scheduleId);

    }
}
